from flask import request
from flask_jwt_extended import jwt_required
from flask_restx import Namespace, Resource, fields

from app1 import db
from app1.models import KmsAppInfo

# 创建 Flask-RESTx 命名空间
ns_app_info = Namespace('ns_app_info', description='应用信息管理')

# ========================== 输入/输出模型 ==========================
# 输出模型
app_info_model = ns_app_info.model('KmsAppInfo', {
    'service_catalog': fields.String(required=True, description='服务目录编号'),
    'service_name': fields.String(required=True, description='服务名'),
    'en_short_name': fields.String(required=True, description='英文简称'),
    'alarm_alias': fields.String(required=True, description='告警别名'),
    'role_a': fields.String(required=True, description='A角'),
    'role_b': fields.String(required=True, description='B角'),
    'ha_grade': fields.String(required=True, description='可用性级别'),
    'dr_grade': fields.String(required=True, description='灾备级别'),
    'service_time': fields.String(required=True, description='服务时间'),
    'system_platform': fields.String(required=True, description='系统平台'),
    'dev_org': fields.String(required=True, description='开发单位'),
    'importance_grade': fields.String(required=True, description='重要性分级'),
    'developer': fields.String(description='开发项目组')
})

# 统一响应模型
response_app_info_model = ns_app_info.model('Response_AppInfo', {
    'message': fields.Nested(ns_app_info.model('Message_AppInfo', {
        'result': fields.Integer(description='0=成功 1=失败'),
        'result_text': fields.String(description='结果描述'),
        'count': fields.Integer(description='总记录数'),
        'data': fields.List(fields.Nested(app_info_model))
    }))
})

# 条件 + 分页查询模型
app_info_query_model = ns_app_info.model('AppInfoQuery', {
    'service_catalog': fields.String(default='', description='服务目录编号'),
    'service_name': fields.String(default='', description='服务名'),
    'en_short_name': fields.String(default='', description='英文简称'),
    'alarm_alias': fields.String(default='', description='告警别名'),
    'page': fields.Integer(default=1, description='页码'),
    'size': fields.Integer(default=20, description='每页条数')
})

# 新增模型
app_info_add_model = ns_app_info.model('AppInfoAdd', {
    'service_catalog': fields.String(required=True, description='服务目录编号'),
    'service_name': fields.String(required=True, description='服务名'),
    'en_short_name': fields.String(required=True, description='英文简称'),
    'alarm_alias': fields.String(required=True, description='告警别名'),
    'role_a': fields.String(required=True, description='A角'),
    'role_b': fields.String(required=True, description='B角'),
    'ha_grade': fields.String(required=True, description='可用性级别'),
    'dr_grade': fields.String(required=True, description='灾备级别'),
    'service_time': fields.String(required=True, description='服务时间'),
    'system_platform': fields.String(required=True, description='系统平台'),
    'dev_org': fields.String(required=True, description='开发单位'),
    'importance_grade': fields.String(required=True, description='重要性分级'),
    'developer': fields.String(description='开发项目组')
})

# 删除模型
app_info_del_model = ns_app_info.model('AppInfoDelete', {
    'service_catalog': fields.String(required=True, description='服务目录编号'),
    'en_short_name': fields.String(required=True, description='英文简称')
})

# 更新模型
app_info_upd_model = ns_app_info.model('AppInfoUpdate', {
    'service_catalog': fields.String(required=True, description='服务目录编号'),
    'service_name': fields.String(required=True, description='服务名'),
    'en_short_name': fields.String(required=True, description='英文简称'),
    'alarm_alias': fields.String(required=True, description='告警别名'),
    'role_a': fields.String(required=True, description='A角'),
    'role_b': fields.String(required=True, description='B角'),
    'ha_grade': fields.String(required=True, description='可用性级别'),
    'dr_grade': fields.String(required=True, description='灾备级别'),
    'service_time': fields.String(required=True, description='服务时间'),
    'system_platform': fields.String(required=True, description='系统平台'),
    'dev_org': fields.String(required=True, description='开发单位'),
    'importance_grade': fields.String(required=True, description='重要性分级'),
    'developer': fields.String(description='开发项目组')
})

# 单条查询模型
app_info_get_model = ns_app_info.model('AppInfoGet', {
    'en_short_name': fields.String(required=True, description='英文简称')
})


# ========================== 1. 分页+条件查询 ==========================
@ns_app_info.route('/app_info_list')
class AppInfoListResource(Resource):
    # @jwt_required()
    @ns_app_info.expect(app_info_query_model)
    @ns_app_info.marshal_with(response_app_info_model)
    def post(self):
        """条件+分页查询  应用信息"""
        data = request.get_json()

        query = KmsAppInfo.query

        # 条件过滤
        if data.get('service_catalog'):
            query = query.filter(KmsAppInfo.service_catalog.like(f"%{data['service_catalog']}%"))
        if data.get('service_name'):
            query = query.filter(KmsAppInfo.service_name.like(f"%{data['service_name']}%"))
        if data.get('en_short_name'):
            query = query.filter(KmsAppInfo.en_short_name.like(f"%{data['en_short_name']}%"))
        if data.get('alarm_alias'):
            query = query.filter(KmsAppInfo.alarm_alias.like(f"%{data['alarm_alias']}%"))

        page = max(1, data.get('page', 1))
        size = max(1, data.get('size', 20))
        total = query.count()
        rows = query.limit(size).offset((page - 1) * size).all()

        return {
            'message': {
                'result': 0,
                'result_text': '查询成功',
                'count': total,
                'data': [r.to_dict() for r in rows]
            }
        }


# ========================== 2. 新增 ==========================
@ns_app_info.route('/app_info_create')
class AppInfoCreateResource(Resource):
    # @jwt_required()
    @ns_app_info.expect(app_info_add_model)
    @ns_app_info.marshal_with(response_app_info_model)
    def post(self):
        """新增  应用信息"""
        data = request.get_json()

        # 必填字段校验
        required_fields = [
            'service_catalog', 'service_name', 'en_short_name', 'alarm_alias',
            'role_a', 'role_b', 'ha_grade', 'dr_grade', 'service_time',
            'system_platform', 'dev_org', 'importance_grade'
        ]
        missing = [f for f in required_fields if not data.get(f)]
        if missing:
            return {
                'message': {
                    'result': 1,
                    'result_text': f'以下字段不能为空: {", ".join(missing)}',
                    'count': 0, 'data': []
                }
            }, 400

        # 检查主键是否已存在
        if KmsAppInfo.query.filter_by(
                service_catalog=data['service_catalog'],
                en_short_name=data['en_short_name']
        ).first():
            return {
                'message': {
                    'result': 1,
                    'result_text': '该服务目录编号和英文简称的组合已存在',
                    'count': 0, 'data': []
                }
            }, 400

        new_row = KmsAppInfo(
            service_catalog=data['service_catalog'],
            service_name=data['service_name'],
            en_short_name=data['en_short_name'],
            alarm_alias=data['alarm_alias'],
            role_a=data['role_a'],
            role_b=data['role_b'],
            ha_grade=data['ha_grade'],
            dr_grade=data['dr_grade'],
            service_time=data['service_time'],
            system_platform=data['system_platform'],
            dev_org=data['dev_org'],
            importance_grade=data['importance_grade'],
            developer=data.get('developer', '')
        )

        try:
            db.session.add(new_row)
            db.session.commit()
            return {
                'message': {
                    'result': 0,
                    'result_text': '创建成功',
                    'count': 1,
                    'data': [new_row.to_dict()]
                }
            }, 201
        except Exception as e:
            db.session.rollback()
            return {
                'message': {
                    'result': 1,
                    'result_text': f'创建失败: {str(e)}',
                    'count': 0, 'data': []
                }
            }, 500


# ========================== 3. 删除 ==========================
@ns_app_info.route('/app_info_delete')
class AppInfoDeleteResource(Resource):
    # @jwt_required()
    @ns_app_info.expect(app_info_del_model)
    @ns_app_info.marshal_with(response_app_info_model)
    def post(self):
        """根据主键删除  应用信息"""
        data = request.get_json()

        row = KmsAppInfo.query.filter_by(
            service_catalog=data['service_catalog'],
            en_short_name=data['en_short_name']
        ).first()

        if not row:
            return {
                'message': {
                    'result': 1,
                    'result_text': '记录不存在',
                    'count': 0, 'data': []
                }
            }, 404

        try:
            db.session.delete(row)
            db.session.commit()
            return {
                'message': {
                    'result': 0,
                    'result_text': '删除成功',
                    'count': 1,
                    'data': [row.to_dict()]
                }
            }
        except Exception as e:
            db.session.rollback()
            return {
                'message': {
                    'result': 1,
                    'result_text': f'删除失败: {str(e)}',
                    'count': 0, 'data': []
                }
            }, 500


# ========================== 4. 更新 ==========================
@ns_app_info.route('/app_info_update')
class AppInfoUpdateResource(Resource):
    # @jwt_required()
    @ns_app_info.expect(app_info_upd_model)
    @ns_app_info.marshal_with(response_app_info_model)
    def post(self):
        """更新  应用信息"""
        data = request.get_json()

        # 必填字段校验
        required_fields = [
            'service_name', 'alarm_alias', 'role_a', 'role_b', 'ha_grade',
            'dr_grade', 'service_time', 'system_platform', 'dev_org', 'importance_grade'
        ]
        missing = [f for f in required_fields if not data.get(f)]
        if missing:
            return {
                'message': {
                    'result': 1,
                    'result_text': f'以下字段不能为空: {", ".join(missing)}',
                    'count': 0, 'data': []
                }
            }, 400

        row = KmsAppInfo.query.filter_by(
            service_catalog=data['service_catalog'],
            en_short_name=data['en_short_name']
        ).first()

        if not row:
            return {
                'message': {
                    'result': 1,
                    'result_text': '记录不存在',
                    'count': 0, 'data': []
                }
            }, 404

        try:
            # 更新字段
            row.service_name = data['service_name']
            row.alarm_alias = data['alarm_alias']
            row.role_a = data['role_a']
            row.role_b = data['role_b']
            row.ha_grade = data['ha_grade']
            row.dr_grade = data['dr_grade']
            row.service_time = data['service_time']
            row.system_platform = data['system_platform']
            row.dev_org = data['dev_org']
            row.importance_grade = data['importance_grade']
            row.developer = data.get('developer', '')

            db.session.commit()
            return {
                'message': {
                    'result': 0,
                    'result_text': '更新成功',
                    'count': 1,
                    'data': [row.to_dict()]
                }
            }
        except Exception as e:
            db.session.rollback()
            return {
                'message': {
                    'result': 1,
                    'result_text': f'更新失败: {str(e)}',
                    'count': 0, 'data': []
                }
            }, 500


# ========================== 5. 单条查询 ==========================
@ns_app_info.route('/app_info_get')
class AppInfoGetResource(Resource):
    # @jwt_required()
    @ns_app_info.expect(app_info_get_model)
    @ns_app_info.marshal_with(response_app_info_model)
    def post(self):
        """根据英文简称查询单条  应用信息"""
        data = request.get_json()

        en_short_name = data.get('en_short_name', '').strip()
        if not en_short_name:
            return {
                'message': {
                    'result': 1,
                    'result_text': 'en_short_name 不能为空',
                    'count': 0,
                    'data': []
                }
            }, 400

        row = KmsAppInfo.query.filter_by(en_short_name=en_short_name).first()

        if not row:
            return {
                'message': {
                    'result': 1,
                    'result_text': '记录不存在',
                    'count': 0,
                    'data': []
                }
            }, 404

        return {
            'message': {
                'result': 0,
                'result_text': '查询成功',
                'count': 1,
                'data': [row.to_dict()]
            }
        }


# ========================== 6. 获取所有记录（无分页） ==========================
@ns_app_info.route('/app_info_all')
class AppInfoAllResource(Resource):
    # @jwt_required()
    @ns_app_info.marshal_with(response_app_info_model)
    def get(self):
        """获取所有  应用信息"""
        rows = KmsAppInfo.query.all()

        return {
            'message': {
                'result': 0,
                'result_text': '查询成功',
                'count': len(rows),
                'data': [r.to_dict() for r in rows]
            }
        }